﻿using BaoShouTangServer.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Web;

namespace BaoShouTangServer.Service
{
    public class Util
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public static string SendMailByGmail(string Sender, string SenderPassword, string Addressee, string maildisplayName, string mailSubject, string mailBody, long Z派工id)
        {
            Z_派工 z派工 = SqlSugarHelp.scope.Queryable<Z_派工>().Where(it => it.id == Z派工id).First();
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential("444068843@qq.com", "hvtcihgrdglrcada");
            SmtpServer.Port = 587;
            SmtpServer.Host = "smtp.qq.com";
            SmtpServer.EnableSsl = true;
            mail = new MailMessage();
            String[] addr = Addressee.Split(',');
            try
            {
                mail.IsBodyHtml = true;
                mail.From = new MailAddress("444068843@qq.com", "工票下达了", System.Text.Encoding.UTF8);
                Byte i;
                for (i = 0; i < addr.Length; i++)
                    mail.To.Add("447275103@qq.com");
                mail.To.Add("444068843@qq.com");
                mail.Subject = "工票下达了";
                //mail.Body = "<img alt='' src=cid:ewen>";
                MemoryStream me = new MemoryStream(z派工.工票二维码);
                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(me, "工票二维码.png");
                mail.Attachments.Add(attachment);

                string mesg = "您的工票已送达。订单号[" + z派工.订单号 + "]。订单行号[" + z派工.订单行号 + "]。产品编号["+z派工.产品编号+"]。产品名称[" + z派工.产品名称 + "]。工序名称[" + z派工.工序名称 + "]。派工数量[" + z派工.派工数量 + "]。";

                string plainTextBody = mesg+"如果你邮件客户端不支持HTML格式，或者你切换到“普通文本”视图，将看到此内容";
                mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainTextBody, null, "text/plain"));

                //HTML格式邮件的内容
                string htmlBodyContent = mesg;
                htmlBodyContent += "<img src=\"cid:" + attachment.ContentId + "\"/>";   //注意此处嵌入的图片资源
                AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html");
                LinkedResource lrImage = new LinkedResource(me, "image/gif");
                lrImage.ContentId = attachment.ContentId; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ，如果设置不正确，请不会显示图片
                htmlBody.LinkedResources.Add(lrImage);
                mail.AlternateViews.Add(htmlBody);




                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                //mail.ReplyTo = new MailAddress(Addressee);
                SmtpServer.Send(mail);
                //Response.Write("<script>alert('发送成功！');</script>");
                return "";
            }
            catch (Exception ex)
            {
                //Response.Write(ex.ToString());
                return ex.ToString();
            }
        }

        public static void SendWeChatWithImage(long Z派工id, out string msg)
        {
            try
            {
                string corpid = ConfigurationManager.AppSettings["corpid"].ToString();
                string corpsecret = ConfigurationManager.AppSettings["corpsecret"].ToString();
                //string tokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx07a8e13a802f95eb&corpsecret=JsiQ8Zr40bTj-OwwazKT1asuO3B2fxYNj5iHhr-i15XEoXaAKJggypeZ51_J4_iM";
                string tokenurl = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
                Dictionary<string, string> dicToken = HttpHelper.HttpGet<Dictionary<string, string>>(tokenurl);
                string token = dicToken["access_token"];

                string imgurl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+token+ "&type=image";
                Z_派工 z派工 = SqlSugarHelp.scope.Queryable<Z_派工>().Where(it => it.id == Z派工id).First();
                if (z派工 == null)
                {
                    msg = "没有查询到该工票信息";
                    return;
                }

                //查这个产品 这个工序，以前的质检信息
                List<Z_派工_报工质检> z_报工质检s = SqlSugarHelp.scope.Queryable<Z_派工_报工质检>().Where(it => it.产品编号 == z派工.产品编号 && it.工序编号 == z派工.工序编号 && it.判定结果 == "拒收").ToList();

                string 拒收信息 = "";
                if (z_报工质检s != null && z_报工质检s.Count > 0)
                {
                    拒收信息 = $"以前拒收过{z_报工质检s.Count}次。不良原因有：[" + string.Join(",", z_报工质检s.Select(z => z.不良原因).Distinct()) + "]。";
                }

                //查询物料
                Inventory inventory = SqlSugarHelp.scope.Queryable<Inventory>().Where(it => it.cInvCode == z派工.产品编号).First();

                //查询这个订单的上一道工序
                int.TryParse(z派工.加工顺序, out int 加工顺序);
                string 前面的人信息 = "";
                if (加工顺序 > 10)
                {
                    string 上一道工序 = (加工顺序 - 10).ToString().PadLeft(4,'0');
                    List<Z_派工> z派工上一道工序 = SqlSugarHelp.scope.Queryable<Z_派工>()
                                                                   .IgnoreColumns(it => it.工票二维码)
                                                                .Where(it => it.订单号 == z派工.订单号 && it.订单行号 == z派工.订单行号 && it.加工顺序 == 上一道工序).ToList();
                    if (z派工上一道工序 != null && z派工上一道工序.Count > 0)
                    {
                        //List<Z_派工> z派工上一道工序 所有的cUser_Name，以逗号分开
                        前面的人信息 = $"上一道工序是[{z派工上一道工序[0].加工顺序}],工序名称:{z派工上一道工序[0].工序名称}, {string.Join(",", z派工上一道工序.Select(z => z.cUser_Name).Distinct())}。 ";

                    }
                }
                 
               string imgResponse = HttpHelper.HttpPost("工票", z派工.工票二维码, imgurl);

                Dictionary<string, string> dicImgResponse = JsonExtends.ToEntity<Dictionary<string, string>>(imgResponse);
                string mediaId = dicImgResponse["media_id"];
                string mesgurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
                WeChatImage weChatImage = new WeChatImage();
                //发给开发者自己以及管理员
                string orgtouser = ConfigurationManager.AppSettings["orgtouser"].ToString();
                //weChatImage.touser = "447275103@qq.com|baij45";
                weChatImage.touser = orgtouser + "|" + z派工.微信号;
                weChatImage.msgtype = "image";
                weChatImage.agentid = 1000002;
                weChatImage.image = new Image { media_id = mediaId };
                string mesg = "["+z派工.cUser_Name+"]"+"您的工票已送达。订单号[" + z派工.订单号 + "]。订单行号[" + z派工.订单行号 + "]。产品编号[" + z派工.产品编号 + "]。物料代码["+inventory?.cInvAddCode+"]。产品名称[" + z派工.产品名称 + "]。厂别["+z派工.厂别+ "]。本道工序[" + z派工.加工顺序 + "]。工序名称[" + z派工.工序名称 +"]。开工日期["+z派工.开工日期.GetValueOrDefault().ToString("yyy-MM-dd") + "]。计划完工日期["+z派工.计划完工日期.GetValueOrDefault().ToString("yyy-MM-dd") + "]。派工数量[" + z派工.派工数量 + "]。";
               mesg = mesg + 前面的人信息;
               
                if (string.IsNullOrEmpty(拒收信息) == false)
                {
                    mesg = mesg + 拒收信息;
                }
                weChatImage.text = new Text { content = mesg };
                //发送二维码图片
                string QRCodeResponse = HttpHelper.HttpPost(mesgurl,JsonExtends.ToJson(weChatImage));
                Dictionary<string, string> dicQRCodeResponse = JsonExtends.ToEntity<Dictionary<string, string>>(QRCodeResponse);
                msg = dicQRCodeResponse["errmsg"];
                Logger.Warn(msg+z派工.ToString());
                //发送工票信息
                weChatImage.msgtype = "text";
                string TextResponse = HttpHelper.HttpPost(mesgurl, JsonExtends.ToJson(weChatImage));
                Dictionary<string, string> dicTextResponse = JsonExtends.ToEntity<Dictionary<string, string>>(TextResponse);
                msg = dicTextResponse["errmsg"];

                //更新发送时间
                z派工.发送日期 = DateTime.Now;
                SqlSugarHelp.scope.Updateable(z派工).UpdateColumns(it => it.发送日期).ExecuteCommand();
            }
            catch (Exception e)
            {
                msg = e.Message;
            }
        }

        public static void SendWeChatWithImageQC(Guid Z派工id, out string msg)
        {
            try
            {
                string corpid = ConfigurationManager.AppSettings["corpid"].ToString();
                string corpsecret = ConfigurationManager.AppSettings["corpsecret"].ToString();
                //string tokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx07a8e13a802f95eb&corpsecret=JsiQ8Zr40bTj-OwwazKT1asuO3B2fxYNj5iHhr-i15XEoXaAKJggypeZ51_J4_iM";
                string tokenurl = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
                Dictionary<string, string> dicToken = HttpHelper.HttpGet<Dictionary<string, string>>(tokenurl);
                string token = dicToken["access_token"];

                Z_派工_报工质检 z派工质检 = SqlSugarHelp.scope.Queryable<Z_派工_报工质检>().Where(it => it.guid == Z派工id).First();
                if (z派工质检 == null)
                {
                    msg = "没有查询到该工票信息";
                    return;
                }

                //查询物料
                Inventory inventory = SqlSugarHelp.scope.Queryable<Inventory>().Where(it => it.cInvCode == z派工质检.产品编号).First();

                string 前面的人信息 = "";
                string mesgurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
                WeChatImage weChatImage = new WeChatImage();
                //发给开发者自己以及管理员
                string orgtouser = ConfigurationManager.AppSettings["qctouser"].ToString();
                //weChatImage.touser = "447275103@qq.com|baij45";
                weChatImage.touser = orgtouser + "|" + z派工质检.微信号;
                weChatImage.agentid = 1000002;
                string mesg = "[" + z派工质检.cUser_Name + "]"+"您的报工质检未通过，拒收原因:" + z派工质检.不良原因+ "。工票信息：订单号[" + z派工质检.订单号 + "]。订单行号[" + z派工质检.订单行号 + "]。产品编号[" + z派工质检.产品编号 + "]。物料代码[" + inventory?.cInvAddCode + "]。产品名称[" + z派工质检.产品名称 + "]。厂别[" + z派工质检.厂别 + "]。本道工序[" + z派工质检.加工顺序 + "]。工序名称[" + z派工质检.工序名称 + "]。开工日期[" + z派工质检.开工日期.GetValueOrDefault().ToString("yyy-MM-dd") + "]。计划完工日期[" + z派工质检.计划完工日期.GetValueOrDefault().ToString("yyy-MM-dd") + "]。派工数量[" + z派工质检.派工数量 + "]。";
                mesg = mesg + 前面的人信息;
                weChatImage.text = new Text { content = mesg };
                //发送工票信息
                weChatImage.msgtype = "text";
                string TextResponse = HttpHelper.HttpPost(mesgurl, JsonExtends.ToJson(weChatImage));
                Dictionary<string, string> dicTextResponse = JsonExtends.ToEntity<Dictionary<string, string>>(TextResponse);
                msg = dicTextResponse["errmsg"];

                //更新发送时间
                z派工质检.发送日期 = DateTime.Now;
                SqlSugarHelp.scope.Updateable(z派工质检).UpdateColumns(it => it.发送日期).ExecuteCommand();
            }
            catch (Exception e)
            {
                msg = e.Message;
            }
        }

        public static void SendWeChatWithText(string wechatcode,string sendmsg, out string msg)
        {
            try
            {
                string corpid = ConfigurationManager.AppSettings["corpid"].ToString();
                string corpsecret = ConfigurationManager.AppSettings["corpsecret"].ToString();
                //string tokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx07a8e13a802f95eb&corpsecret=JsiQ8Zr40bTj-OwwazKT1asuO3B2fxYNj5iHhr-i15XEoXaAKJggypeZ51_J4_iM";
                string tokenurl = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
                Dictionary<string, string> dicToken = HttpHelper.HttpGet<Dictionary<string, string>>(tokenurl);
                string token = dicToken["access_token"];

                //string imgurl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=image";
                //Z_派工 z派工 = SqlSugarHelp.scope.Queryable<Z_派工>().Where(it => it.id == Z派工id).First();
                //if (z派工 == null)
                //{
                //    msg = "没有查询到该工票信息";
                //    return;
                //}

                //string imgResponse = HttpHelper.HttpPost("工票", z派工.工票二维码, imgurl);

                //Dictionary<string, string> dicImgResponse = JsonExtends.ToEntity<Dictionary<string, string>>(imgResponse);
                //string mediaId = dicImgResponse["media_id"];
                string mesgurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
                WeChatImage weChatImage = new WeChatImage();
                //发给开发者自己以及管理员
                string orgtouser = ConfigurationManager.AppSettings["orgtouser"].ToString();
                //weChatImage.touser = "447275103@qq.com|baij45";
                weChatImage.touser = orgtouser + "|" + wechatcode;
                //weChatImage.msgtype = "image";
                weChatImage.agentid = 1000002;
                //weChatImage.image = new Image { media_id = mediaId };
                string mesg = sendmsg;
                weChatImage.text = new Text { content = mesg };
                //发送二维码图片
                //string QRCodeResponse = HttpHelper.HttpPost(mesgurl, JsonExtends.ToJson(weChatImage));
                //Dictionary<string, string> dicQRCodeResponse = JsonExtends.ToEntity<Dictionary<string, string>>(QRCodeResponse);
                //msg = dicQRCodeResponse["errmsg"];
                //发送工票信息
                weChatImage.msgtype = "text";
                string TextResponse = HttpHelper.HttpPost(mesgurl, JsonExtends.ToJson(weChatImage));
                Dictionary<string, string> dicTextResponse = JsonExtends.ToEntity<Dictionary<string, string>>(TextResponse);
                msg = dicTextResponse["errmsg"];
                //更新发送时间
                //z派工.发送日期 = DateTime.Now;
                //SqlSugarHelp.scope.Updateable(z派工).UpdateColumns(it => it.发送日期).ExecuteCommand();
            }
            catch (Exception e)
            {
                msg = e.Message;
            }
        }


    }
}